package cn.stylefeng.guns.sys.modular.system.service;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.ExcelUtil;
import cn.stylefeng.guns.sys.modular.system.db4.service.BizShopService;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.mapper.*;
import cn.stylefeng.guns.sys.modular.system.model.params.TakeAwayTxlParam;
import cn.stylefeng.guns.sys.modular.system.model.result.TakeAwayResult;
import cn.stylefeng.guns.sys.modular.system.model.result.YyjlResult;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class BtyTxlService extends ServiceImpl<BtyTxlMapper, BtyTxl> {

    @Autowired
    private BtyTxlMapper mapper;
    @Resource
    private BtyRegionMapper regionMapper;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private UserMapper userMapper;
    @Autowired
    BizShopService bizShopService;
    @Resource
    private BtyCwmService btyCwmService;
    @Autowired
    private BtyBrandMapper btyBrandMapper;
    @Autowired
    private BtyWmtxlMapper btyWmtxlMapper;
    @Autowired
    private BtyWmtxlService btyWmtxlService;
    @Autowired
    private AttendAuditBtyAreaMapper btyAreaMapper;
    @Resource
    private BtyTxlRySMapper btyTxlRySMapper;

    /**
     * 获取档案管理列表
     *
     * @author fengshuonan
     * @Date 2018/12/23 6:05 PM
     */

    public Page<Map<String, Object>> list(String ctbh, String dm, String csqy, String yyjlqy, String dd, String beginTime, String endTime, Integer status) {
        Page page = LayuiPageFactory.defaultPage();
        return this.mapper.list(page, ctbh, dm, csqy, yyjlqy, dd, beginTime, endTime, status);
    }


    /**
     * 同步钉钉手机号
     */
    public void updateLxfs(String oldTels,String lxfs){
        //通讯录表中查找是否有符合的手机号
        List<BtyTxlRyS> btyTxlRySList=new LambdaQueryChainWrapper<>(btyTxlRySMapper)
                .eq(BtyTxlRyS::getLxfs,oldTels)
                .list();
        //根据已查到的手机号匹配通讯录表手机号 匹配到先更新保存原手机号，然后替换新手机号
        btyTxlRySList.forEach(i -> {
            //判断手机号库中手机号是否与新手机号一致
            if (!i.getLxfs().equals(lxfs)) {
                LambdaQueryWrapper<BtyTxlRyS> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(BtyTxlRyS::getLxfs,lxfs);
                BtyTxlRyS btyTxlRySOne = btyTxlRySMapper.selectOne(queryWrapper);
                if(btyTxlRySOne==null){
                    i.setOldTels(i.getLxfs());
                    i.setLxfs(lxfs);
                    //引入通讯录表数据操作层
                    btyTxlRySMapper.updateById(i);
                }
            }
        });
    }

    public void updateBtyTxlYytel(String oldTels,String yytel){
        //通讯录表中查找是否有符合的手机号
        List<BtyTxl> btyTxlList=new LambdaQueryChainWrapper<>(this.mapper)
                .eq(BtyTxl::getYytel,oldTels)
                .list();
        //根据已查到的手机号匹配培训表手机号 匹配到先更新保存原手机号，然后替换新手机号
        btyTxlList.forEach(i -> {
            //判断已查询到的手机号与新手机号是否一致
            if (!i.getYytel().equals(yytel)) {
                LambdaQueryWrapper<BtyTxl> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(BtyTxl::getYytel,yytel);
                BtyTxl btyTxlOne = this.baseMapper.selectOne(queryWrapper);
                if(btyTxlOne==null){
                    i.setOldTels(i.getYytel());
                    i.setYytel(yytel);
                    //引入通讯录表数据操作层
                    this.mapper.updateById(i);
                }
            }
        });
    }

    /**
     * 获取通讯录列表
     */
    public void listExport(String ctbh, String dm, String csqy, String yyjl, String dd, String beginTime, String endTime, Integer status, HttpServletResponse response) {
//        return this.mapper.listExport(ctbh, dm, csqy, yyjl, dd, beginTime, endTime);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String number = sdf.format(new Date());
        // 查询数据
        List<BtyTxl> maps = this.baseMapper.listExport(ctbh, dm, csqy, yyjl, dd, beginTime, endTime, status);

        String fileName = number;
        String path = "D:\\" + "xls\\";
        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs(); //创建目录
        }
        String url = path + fileName + ".xls";
        try {
            //map数据
            List<String[]> dataset = new ArrayList<>();
            for (int i = 0; i < maps.size(); i++) {
                String[] arr = new String[20];
                arr[0] = maps.get(i).getCsqy() == null ? "" : maps.get(i).getCsqy();
                arr[1] = maps.get(i).getSimpleName() == null ? "" : maps.get(i).getSimpleName();
                arr[2] = maps.get(i).getYyjlqy() == null ? "" : maps.get(i).getYyjlqy();
                arr[3] = maps.get(i).getYytel() == null ? "" : maps.get(i).getYytel();
                arr[4] = maps.get(i).getDd() == null ? "" : maps.get(i).getDd();
                arr[5] = maps.get(i).getCtbh() == null ? "" : maps.get(i).getCtbh();
                arr[6] = maps.get(i).getCwm() == null ? "" : maps.get(i).getCwm();
                arr[7] = maps.get(i).getDm() == null ? "" : maps.get(i).getDm();
                arr[8] = maps.get(i).getTiancai() == null ? "" : maps.get(i).getTiancai();
                arr[9] = maps.get(i).getElm() == null ? "" : maps.get(i).getElm();
                arr[10] = maps.get(i).getMt() == null ? "" : maps.get(i).getMt();
                arr[11] = maps.get(i).getKysj() == null ? "" : maps.get(i).getKysj();
                arr[12] = maps.get(i).getCtdh() == null ? "" : maps.get(i).getCtdh();
                arr[13] = maps.get(i).getCtdz() == null ? "" : maps.get(i).getCtdz();
                arr[14] = maps.get(i).getFzr() == null ? "" : maps.get(i).getFzr();
                arr[15] = maps.get(i).getLxfs() == null ? "" : maps.get(i).getLxfs();
                arr[16] = maps.get(i).getDdz() == null ? "" : maps.get(i).getDdz();
                arr[17] = maps.get(i).getSta() == null ? "" : maps.get(i).getSta();
                arr[18] = maps.get(i).getYyzzmc() == null ? "" : maps.get(i).getYyzzmc();
                arr[19] = maps.get(i).getShxydm() == null ? "" : maps.get(i).getShxydm();
                dataset.add(arr);
            }
            //外卖导出表头
            String[] handers1 = {"所属区域", "二级区域", "营运经理区域", "营运经理电话", "督导", "餐厅编号", "财务码", "店名", "天财店名", "饿了么店名", "美团店名", "开业时间", "餐厅电话", "餐厅地址", "店长", "联系方式", "大店长","餐厅状态","营业执照名称","社会信用代码"};
            //对象
            ExcelExp fymx = new ExcelExp("通讯录", handers1, dataset);
            List<ExcelExp> mysheet = new ArrayList<>();
            mysheet.add(fymx);
            //生成sheet
            ExcelUtil.exportManySheetExcel(url, mysheet);
            //下载sheet
            ExcelUtil.getExcel(url, fileName, response);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public BtyTxl getByID(Long id) {
        return this.mapper.getByID2(id);
    }


    public void delete(Long id) {
        //删除bty_txl表数据
        this.mapper.delete(id);
        //删除bty_txl_ry表数据
        this.mapper.deleteRy(id);
    }

    public int updateTxl(BtyTxl btyTxl) {
        return this.mapper.updateTxl(btyTxl);
    }

    public int updateCtbh(BtyTxl btyTxl) {
        return this.mapper.updateCtbh(btyTxl);
    }

    @Transactional(rollbackFor = Exception.class)
    public Object addfzr(BtyTxlRY btyTxlRY) {
        int flag = 0;

        //营运经理助理直接新增
        if (btyTxlRY.getZw().equals("营运经理助理")){
            //查询该人是否存在
            int sum = mapper.getSum(btyTxlRY);
            if (sum == 0){
                flag = mapper.addfzr(btyTxlRY);

                //该手机号已存在
            }else {
                return 1;
            }


        }else {
            //查询数据库中是否存在该数据
            int count = mapper.selectCount(btyTxlRY.getSsctdm(), btyTxlRY.getZw());
            if (count == 0){
                flag = mapper.addfzr(btyTxlRY);
            }else {
                flag = mapper.updateTxlRY(btyTxlRY);
            }
        }

        if(flag>0){
         String ctbh=btyTxlRY.getSsctbh();
         List<BtyTxl>list=mapper.listByCtbh(ctbh);
         BtyRegion btyRegion=new BtyRegion();
         if(ToolUtil.isNotEmpty(list)){
             for (int i = 0; i < list.size(); i++) {
               String yyjl=list.get(i).getYyjlqy();
               String dm=list.get(i).getDm();
               String dd=list.get(i).getDd();
               btyRegion.setYyjl(yyjl);
               btyRegion.setDm(dm);
               btyRegion.setDd(dd);
               this.regionMapper.insert(btyRegion);
             }
          }
        }
        return 0;
    }

    @Transactional(rollbackFor = Exception.class)
    public Integer addct(BtyTxl btyTxl) {
        //店名判重
        if(this.mapper.selectDm(btyTxl.getDm()) > 0){
            return 1;

            //餐厅编号判重
        }else if(btyTxl.getCtbh() != null && !"".equals(btyTxl.getCtbh()) && this.mapper.selectBh(btyTxl.getCtbh()) > 0){
            return 2;

        }
        else {
            btyTxl.setStatus(1);//正常
            this.mapper.addct(btyTxl);
            return 0;
        }
    }

    public Page<Map<String, Object>> view(Long id) {
        Page page = LayuiPageFactory.defaultPage();
        return this.mapper.view(page, id);
    }

    public int view_delete(Long pid) {
        return this.mapper.view_delete(pid);
    }

    public BtyTxlRY view_update_getByID(Long pid) {
        return this.mapper.view_update_getByID(pid);
    }

    public int view_update(BtyTxlRY btyTxlRY) {

        return this.mapper.view_update(btyTxlRY);
    }

    public List<BtyTxl> selectTerm(String term) {
        return this.mapper.selectTerm(term);
    }

    public List<BtyTxl> select() {
        return mapper.selectSpjy();
    }

    //查找营运经理openID
    public String selectYyjl(String yyjl) {
        return mapper.selectYyjl(yyjl);
    }

    //查询开业时间,餐厅编号
    public BtyTxl getCount(String dm) {
        return mapper.getCount(dm);
    }

    //查询所有营运经理及其电话
    public List<BtyTxl> selectYy(String yyjl) {
        return mapper.selectYy(yyjl);
    }

    /**
     * 修改店长
     */
    @Transactional(rollbackFor = Exception.class)
    public int editPerson(BtyTxl btyTxl) {
        this.updateTxl(btyTxl);
        if(mapper.editPerson(btyTxl)==0){
            btyTxl.setZw("店长");
            this.mapper.addDZ(btyTxl);
        }
        return 0;
    }

    /**
     * 查询督导所属店名
     * @param account
     * @return
     */
    public List<BtyTxl> ddList(String account) {
        return mapper.ddList(account);
    }

    public TakeAwayResult takeAwayTxl(String gcgWsjdId){
        return mapper.takeAwayTxl(gcgWsjdId);
    }

    /**
     * 查询营运经理所属店名
     * @param account
     * @return
     */
    public List<BtyTxl> yyList(String account) {
        return mapper.yyList(account);
    }

    /**
     * 查询店名对应餐厅编号
     * @param dm
     * @return
     */
    public String getBh(String dm) {
        return mapper.getBh(dm);
    }

    public void updateRy(BtyTxl btyTxl) {
        mapper.updateRy(btyTxl);
    }

    /**
     * 导入通讯录excel
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Boolean batchImport(String fileName, MultipartFile file) throws Exception{

        boolean notNull = false;

        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new Exception("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }

        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }

        List<Map<Object, Object>> list = new ArrayList<Map<Object, Object>>();

        //excel中多个sheet表，获取所有sheet表的数量
        int sheets = wb.getNumberOfSheets();
        //循环sheet
        for (int i = 0; i < sheets; i++) {
            Sheet sheet = wb.getSheetAt(i);
            if (sheet != null) {
                notNull = true;
            }

            //循环行
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }

                Map<Object, Object> map = new HashMap<>();

                //循环单元格cell
                for (int cellNum = 0; cellNum <= row.getLastCellNum(); cellNum++) {
                    Cell cell = row.getCell(cellNum);
                    //把单元格的内容转换为字符串
                    if (cell != null) {

                        if (cell.toString().contains("月-")){

                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                            String value = format.format(cell.getDateCellValue());

                            map.put(cellNum, value);
                        }else {
                            cell.setCellType(CellType.STRING);
                            map.put(cellNum, cell.getStringCellValue());
                        }
                    }
                }

                list.add(map);
            }
        }

        List<BtyTxl> txlList = new ArrayList<>();
//        List<BtyTxlRY> txlRYList = new ArrayList<>();

        //循环取出的数据
        for (Map map : list) {

            String csqy = map.get(0) == null ? "" : map.get(0).toString();//城市区域
            String yyjlqy = map.get(1) == null ? "" : map.get(1).toString();//营运经理
            String yytel = map.get(2) == null ? "" : map.get(2).toString();//营运经理电话
            String dd = map.get(3) == null ? "" : map.get(3).toString();//督导
            String ddTel = map.get(4) == null ? "" : map.get(4).toString();//督导电话
            String ddz = map.get(5) == null ? "" : map.get(5).toString();//大店长
            String ddzTel = map.get(6) == null ? "" : map.get(6).toString();//大店长电话
            String ctbh = map.get(7) == null ? "" : map.get(7).toString();//餐厅编号
            String dm = map.get(8) == null ? "" : map.get(8).toString();//店名
            String kysj = map.get(9) == null ? "" : map.get(9).toString();;//开业时间
            String ctdh = map.get(10) == null ? "" : map.get(10).toString();//餐厅电话
            String ctdz = map.get(11) == null ? "" : map.get(11).toString();//餐厅地址
            String dz = map.get(12) == null ? "" : map.get(12).toString();//店长
            String dzTel = map.get(13) == null ? "" : map.get(13).toString();//店长电话
            String spjyxk = map.get(14) == null ? "" : map.get(14).toString();;//食品经营许可证截止时间
            String yyzzfr = map.get(15) == null ? "" : map.get(15).toString();//营业执照法人
            String ctywxgm = map.get(16) == null ? "" : map.get(16).toString();//餐厅意外险
            String ctywxjzsj = map.get(17) == null ? "" : map.get(17).toString();;//餐厅意外险截止时间
            String ctggzrgm = map.get(18) == null ? "" : map.get(18).toString();//餐厅公共责任险
            String ctggzrjzsj = map.get(19) == null ? "" : map.get(19).toString();;//餐厅公共责任险截止时间

            BtyTxl btyTxl = new BtyTxl();
            btyTxl.setCsqy(csqy);
            btyTxl.setYyjlqy(yyjlqy);
            btyTxl.setCtbh(ctbh);
            btyTxl.setDm(dm);
            btyTxl.setYyzzfr(yyzzfr);
            btyTxl.setKysj(kysj);
            btyTxl.setCtdz(ctdz);
            btyTxl.setCtdh(ctdh);
            btyTxl.setSpjyxk(spjyxk);
            btyTxl.setCtywxgm(ctywxgm);
            btyTxl.setCtywxjzsj(ctywxjzsj);
            btyTxl.setCtggzrxgm(ctggzrgm);
            btyTxl.setCtggzrxjzsj(ctggzrjzsj);
            btyTxl.setYytel(yytel);

            btyTxl.setDd(dd);
            btyTxl.setDdTel(ddTel);
            btyTxl.setDz(dz);
            btyTxl.setDzTel(dzTel);
            btyTxl.setDdz(ddz);
            btyTxl.setDdzTel(ddzTel);
            btyTxl.setStatus(1);

            txlList.add(btyTxl);

        }

//        //判断店名，编号是否重复
//        int dmCount = this.mapper.dmCount(txlList);
//
//        //判断编号是否重复
//        int bhCount = this.mapper.bhCount(txlList);

        //删除txl原有数据
        this.mapper.deleteTxl();
        //删除txlRy原有数据
        this.mapper.deleteTxlRY();


        for (BtyTxl btyTxl : txlList) {
            this.mapper.addBtyTxl(btyTxl);//新增txl

            List<BtyTxlRY> txlRYList = new ArrayList<>();

            BtyTxlRY btyTxlRY = new BtyTxlRY();
            btyTxlRY.setZw("督导");//职务
            btyTxlRY.setFzr(btyTxl.getDd());//负责人(督导)
            btyTxlRY.setLxfs(btyTxl.getDdTel()); //联系方式
            btyTxlRY.setSsctdm(btyTxl.getDm());//店名
            btyTxlRY.setSsctbh(btyTxl.getCtbh());//餐厅编号
            btyTxlRY.setBtyTxlId(btyTxl.getId());//通讯录id
            txlRYList.add(btyTxlRY);

            BtyTxlRY btyTxlRY1 = new BtyTxlRY();
            btyTxlRY1.setZw("店长");//职务
            btyTxlRY1.setFzr(btyTxl.getDz());//负责人(店长)
            btyTxlRY1.setLxfs(btyTxl.getDzTel()); //联系方式
            btyTxlRY1.setSsctdm(btyTxl.getDm());//店名
            btyTxlRY1.setSsctbh(btyTxl.getCtbh());//餐厅编号
            btyTxlRY1.setBtyTxlId(btyTxl.getId());//通讯录id
            txlRYList.add(btyTxlRY1);

            BtyTxlRY btyTxlRY2 = new BtyTxlRY();
            btyTxlRY2.setZw("大店长");//职务
            btyTxlRY2.setFzr(btyTxl.getDdz());//负责人(大店长)
            btyTxlRY2.setLxfs(btyTxl.getDdzTel()); //联系方式
            btyTxlRY2.setSsctdm(btyTxl.getDm());//店名
            btyTxlRY2.setSsctbh(btyTxl.getCtbh());//餐厅编号
            btyTxlRY2.setBtyTxlId(btyTxl.getId());//通讯录id
            txlRYList.add(btyTxlRY2);

            this.mapper.addTxlRy(txlRYList);//新增ry
        }


        return notNull;
    }

    public Integer renew(BtyTxl btyTxl) {
        //店名判重
        if ( this.mapper.getDm(btyTxl) > 0 ){
           return 1;

           //餐厅编号判重
        }else if (btyTxl.getCtbh() != null && !"".equals(btyTxl.getCtbh()) && this.mapper.getCtbh(btyTxl) > 0 ){
            return 2;
//
        }else {
            //修改bty_txl表数据
            this.mapper.updateById(btyTxl);
            //同时修改bty_txl_ry表数据(根据关联id修改)
            mapper.updateRy(btyTxl);

            return 0;
        }
    }



    public Integer updateStatus(BtyTxl btyTxl) {

            //修改bty_txl表数据
            this.mapper.updateById(btyTxl);
            return 0;
    }

    /**
     * 查询该营运经理助理对应的营运经理
     * @param account
     * @param phone
     * @return
     */
    public BtyTxl getYyjl(String account, String phone) {
        return this.mapper.getYyjl(account, phone);
    }

    public String getPhone(Long userId) {
        return userMapper.getPhone(userId);
    }

    public Page<Map<String, Object>> listDd(String ctbh, String dm, String csqy, String yyjl, String dd, String beginTime, String endTime, String tel, Integer status) {
        Page page = LayuiPageFactory.defaultPage();
        return this.mapper.listDd(page, ctbh, dm, csqy, yyjl, dd, beginTime, endTime, tel, status);
    }

    public Page<Map<String, Object>> listYy(String ctbh, String dm, String csqy, String yyjl, String dd, String beginTime, String endTime, String tel, Integer status) {
        Page page = LayuiPageFactory.defaultPage();
        return this.mapper.listYy(page, ctbh, dm, csqy, yyjl, dd, beginTime, endTime, tel, status);
    }

    public Page<Map<String, Object>> listZl(String ctbh, String dm, String csqy, String yyjl, String dd, String beginTime, String endTime, String tel, Integer status) {
        Page page = LayuiPageFactory.defaultPage();
        return this.mapper.listZl(page, ctbh, dm, csqy, yyjl, dd, beginTime, endTime, tel, status);
    }


    /**
     * 同步店长信息
     * @return
     */
    public ResponseData updateDz() {

        //获取店长信息
        List<Map> list = bizShopService.getDzlist();
        if(ToolUtil.isNotEmpty(list)){

            //每150条保存一次
            for(int i = 0; i < list.size();){
                int i2 = (i + 150);
                i2 = i2 > list.size() ? list.size() : i2;
                List<Map> sub = list.subList(i, i2);
                this.mapper.updateDz(sub);
                i = i2;
            }

        }
        //修改bty_txl表数据
//        this.mapper.updateDz(btyTxlRY);
        return ResponseData.success();
    }

    /**
     * 督导
     * @param id
     * @return
     */
    public String selectDd(Long id) {
        return mapper.selectDd(id);
    }

    /**
     * 通讯录同步食品经营许可证数据
     * @param btyTxl
     */
    public void edit(BtyTxl btyTxl) {
        mapper.edit(btyTxl);
    }

    /**
     * 更新财务码
     * @return
     */
//    public ResponseData updateCwm() {
//
//        //获取bty_cwm表财务码数据
//        List<BtyCwm> cwmList = btyCwmService.list(new QueryWrapper<BtyCwm>());
//        //获取通讯录没有财务码的店
//        List<BtyTxl> list = baseMapper.cwmList();
//        //bty_brand表中财务码为0的店
//        List<BtyBrand> brandList = btyBrandMapper.cwmList();
//
//
//        for (BtyCwm btyCwm : cwmList) {
//            //通讯录表中存在该店，且财务码为空
//            if (list.stream().filter(w->String.valueOf(w.getDm()).equals(btyCwm.getDm()) && ToolUtil.isEmpty(w.getCwm())).findAny().isPresent()){
//                BtyTxl btyTxl = new BtyTxl();
//                btyTxl.setCwm(btyCwm.getCwm());
//                btyTxl.setDm(btyCwm.getDm());
//                //将财务码同步到通讯录
//                baseMapper.updateCwm(btyTxl);
//            }
//
//            //bty_brand表中存在该店，且财务码 = 0
//            if (brandList.stream().filter(w->String.valueOf(w.getDm()).equals(btyCwm.getDm()) && w.getCwm().equals("0")).findAny().isPresent()){
//                BtyBrand btyBrand = new BtyBrand();
//                btyBrand.setCwm(btyCwm.getCwm());
//                btyBrand.setDm(btyCwm.getDm());
//                //将财务码同步到bty_brand
//                btyBrandMapper.updateCwm(btyBrand);
//            }
//        }
//
//        return ResponseData.success();
//    }


    public ResponseData updateCwm() {

        //获取bty_cwm表财务码数据
        List<BtyCwm> cwmList = btyCwmService.list(new QueryWrapper<BtyCwm>());
        //获取通讯录没有财务码的店(不是山西的)
        List<BtyTxl> list = baseMapper.cwmList();
        //bty_brand表中财务码为0的店(不是山西的)
        List<BtyBrand> brandList = btyBrandMapper.cwmList();


        for (BtyCwm btyCwm : cwmList) {
            //通讯录表中存在该店，且财务码为空
            if (list.stream().filter(w->String.valueOf(w.getDm()).equals(btyCwm.getDm()) && ToolUtil.isEmpty(w.getCwm())).findAny().isPresent()){
                BtyTxl btyTxl = new BtyTxl();
                btyTxl.setCwm(btyCwm.getCwm());
                btyTxl.setDm(btyCwm.getDm());
                //将财务码同步到通讯录
                baseMapper.updateCwm(btyTxl);
            }

            //bty_brand表中存在该店，且财务码 = 0
            if (brandList.stream().filter(w->String.valueOf(w.getDm()).equals(btyCwm.getDm()) && w.getCwm().equals("0")).findAny().isPresent()){
                BtyBrand btyBrand = new BtyBrand();
                btyBrand.setCwm(btyCwm.getCwm());
                btyBrand.setDm(btyCwm.getDm());
                //将财务码同步到bty_brand
                btyBrandMapper.updateCwm(btyBrand);
            }
        }

        return ResponseData.success();
    }
    @Transactional
    public LayuiPageInfo takeAwayTxlList(TakeAwayTxlParam takeAwayTxlParam) {
        Page pageContext = LayuiPageFactory.defaultPage();
        IPage page = this.baseMapper.takeAwayTxlPageList(pageContext, takeAwayTxlParam);
        return LayuiPageFactory.createPageInfo(page);
    }

    public List<TakeAwayResult> takeAwayExportList(TakeAwayTxlParam takeAwayTxlParam) {
        List<TakeAwayResult> list = this.baseMapper.takeAwayExportList(takeAwayTxlParam);
  //      for (TakeAwayResult takeAwayResult : list) {
//            if(takeAwayResult.getMtmingcheng().contains("半天妖烤鱼")&&!takeAwayResult.getMtmingcheng().contains("（")&&!takeAwayResult.getMtmingcheng().contains("(")){
//                String dm=takeAwayResult.getMtmingcheng();
//                String elmDm=dm;
//                String [] dms=dm.split("半天妖烤鱼");
//                String mtDm="半天妖烤鱼"+"（"+dms[1]+")";
//                takeAwayResult.setMtmingcheng(mtDm);
//                takeAwayResult.setElememingcheng(elmDm);
//
//            }else if(takeAwayResult.getMtmingcheng().contains("半天妖烤鱼")&&(takeAwayResult.getMtmingcheng().contains("（")|takeAwayResult.getMtmingcheng().contains("("))){
//                String dm=takeAwayResult.getMtmingcheng();
//                String mtDm=dm;
//                String elmDm=dm.replace("(","").replace("（","")
//                        .replace(")","").replace("）","");
//                takeAwayResult.setMtmingcheng(mtDm);
//                takeAwayResult.setElememingcheng(elmDm);
//
//            }
//            else{
//                String mtDm="半天妖烤鱼"+"（"+takeAwayResult.getMtmingcheng()+")";
//                String elmDm="半天妖烤鱼"+takeAwayResult.getMtmingcheng();
//                takeAwayResult.setMtmingcheng(mtDm);
//                takeAwayResult.setElememingcheng(elmDm);
//            }
//            if(takeAwayResult.getYyjl().equals("汪晓林")){
//                takeAwayResult.setYyjl("潘忠康");
//            }
//            else if(takeAwayResult.getYyjl().equals("王业付")){
//                takeAwayResult.setYyjl("屈玉泉");
//            }
//            else if(takeAwayResult.getYyjl().equals("孙课=姚翠芳")){
//                takeAwayResult.setYyjl("孙课");
//            }
  //      }
        return list;
    }

    public List<YyjlResult> getyyjlList() {
        List<YyjlResult>list=this.baseMapper.getyyjlList();
//        for (YyjlResult yyjlResult : list) {
//            if(yyjlResult.getYyjl().equals("汪晓林")){
//              yyjlResult.setYyjl("潘忠康");
//            }
//           else if(yyjlResult.getYyjl().equals("王业付")){
//                yyjlResult.setYyjl("屈玉泉");
//            }
//           else if(yyjlResult.getYyjl().equals("孙课=姚翠芳")){
//                yyjlResult.setYyjl("孙课");
//            }
//        }
        return list;
    }


    public List<Map> tcList() {
        List<Map>list = this.baseMapper.tcList();
        return list;
    }

    /**
     * 导入外卖通讯录excel
     * @param fileName
     * @param file
     * @return
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public Boolean importWm(String fileName, MultipartFile file) throws Exception{

        boolean notNull = false;

        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new Exception("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }

        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }

        List<Map<Object, Object>> list = new ArrayList<Map<Object, Object>>();

        //excel中多个sheet表，获取所有sheet表的数量
        int sheets = wb.getNumberOfSheets();
        //循环sheet
        for (int i = 0; i < sheets; i++) {
            Sheet sheet = wb.getSheetAt(i);
            if (sheet != null) {
                notNull = true;
            }

            //循环行
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                Row row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }

                Map<Object, Object> map = new HashMap<>();

                //循环单元格cell
                for (int cellNum = 0; cellNum <= row.getLastCellNum(); cellNum++) {
                    Cell cell = row.getCell(cellNum);
                    //把单元格的内容转换为字符串
                    if (cell != null) {

                        if (cell.toString().contains("月-")){

                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                            String value = format.format(cell.getDateCellValue());

                            map.put(cellNum, value);
                        }else {
                            cell.setCellType(CellType.STRING);
                            map.put(cellNum, cell.getStringCellValue());
                        }
                    }
                }

                list.add(map);
            }
        }

        List<BtyWmtxl> txlList = new ArrayList<>();

        //循环取出的数据
        for (Map map : list) {

            Pattern pattern = Pattern.compile("\\s*|\t|\r|\n");

            String yaoma = map.get(0) == null ? "" : map.get(0).toString();//妖码
            Matcher matcher = pattern.matcher(yaoma);
            yaoma = matcher.replaceAll("");

            String yyjl = map.get(1) == null ? "" : map.get(1).toString();//营运经理
            String dm = map.get(2) == null ? "" : map.get(2).toString();//店名
            String elm = map.get(3) == null ? "" : map.get(3).toString();//饿了么店名
            String mt = map.get(4) == null ? "" : map.get(4).toString();//美团店名
            String tiancai = map.get(5) == null ? "" : map.get(5).toString();//天财店名

            BtyWmtxl btyWmtxl = new BtyWmtxl();
            btyWmtxl.setYaoma(yaoma);
            btyWmtxl.setYyjl(yyjl);
            btyWmtxl.setDm(dm);
            btyWmtxl.setElm(elm);
            btyWmtxl.setMt(mt);
            btyWmtxl.setTiancai(tiancai);
            //美团，饿了么都不为空则锁定
            if (ToolUtil.isNotEmpty(elm) && ToolUtil.isNotEmpty(mt)){
                btyWmtxl.setStatus(0);//状态：0->导入，1->添加（导入的不可修改）
            }else {
                btyWmtxl.setStatus(1);//状态：0->导入，1->添加（导入的不可修改）
            }


            txlList.add(btyWmtxl);

        }

        //获取BtyWmtxl中数据

        for (BtyWmtxl btyWmtxl : txlList) {

            //判断BtyWmtxl中是否存在该数据
            int con = btyWmtxlMapper.getYaoma(btyWmtxl);

            if (con == 0){
                btyWmtxlService.save(btyWmtxl);
            }else {
                btyWmtxlMapper.updateWm(btyWmtxl);
            }
        }

        return notNull;
    }

    public LayuiPageInfo wmList(TakeAwayTxlParam takeAwayTxlParam) {
        Page pageContext = LayuiPageFactory.defaultPage();
        IPage page = this.baseMapper.wmList(pageContext, takeAwayTxlParam);
        return LayuiPageFactory.createPageInfo(page);
    }

    public List<TakeAwayResult> wmExportList(TakeAwayTxlParam takeAwayTxlParam) {
        List<TakeAwayResult> list = this.baseMapper.wmExportList(takeAwayTxlParam);
        return list;
    }

    public ResponseData waimaiAddList(BtyWmtxl btyWmtxl) {
        if (ToolUtil.isEmpty(btyWmtxl.getId())){
            btyWmtxl.setStatus(1);//状态：0->导入，1->添加（导入的不可修改）
            btyWmtxlService.save(btyWmtxl);
        }else {
            btyWmtxlMapper.updateWm(btyWmtxl);
        }
        return ResponseData.success();
    }

    /**
     * 同步营运架构
     * @return
     */
    public ResponseData updateYy() {
        //获取营运经理，督导，大店长，店长信息
        List<Map> list = btyAreaMapper.getList();
        if(ToolUtil.isNotEmpty(list)){

            //每150条保存一次
            for(int i = 0; i < list.size();){
                int i2 = (i + 150);
                i2 = i2 > list.size() ? list.size() : i2;
                List<Map> sub = list.subList(i, i2);
                this.mapper.updateYy(sub);//修改营运经理及电话
                i = i2;
            }

            for (Map map : list) {
                String dm = map.get("dm").toString();//店名

                //查询表中是否存在该数据
                int ddCount = mapper.selectCount(dm, "督导");
                //bty_txl_ry表新增数据
                BtyTxlRY btyTxlRY = new BtyTxlRY();
                btyTxlRY.setZw("督导");//职务(督导)
                btyTxlRY.setFzr(ToolUtil.isEmpty(map.get("dd")) ? "" : map.get("dd").toString());//负责人
                btyTxlRY.setLxfs(ToolUtil.isEmpty(map.get("dddh")) ? "" : map.get("dddh").toString());//联系方式
                btyTxlRY.setSsctdm(dm);//店名
                //不存在该数据
                if (ddCount == 0) {
                    mapper.addfzr(btyTxlRY);
                } else {
                    mapper.updateTxlRY(btyTxlRY);
                }

                //查询表中是否存在该数据
                int ddzCount = mapper.selectCount(dm, "大店长");
                //bty_txl_ry表新增数据
                BtyTxlRY btyTxlRY2 = new BtyTxlRY();
                btyTxlRY2.setZw("大店长");//职务(大店长)
                btyTxlRY2.setFzr(ToolUtil.isEmpty(map.get("ddz")) ? "" : map.get("ddz").toString());//负责人
                btyTxlRY2.setLxfs(ToolUtil.isEmpty(map.get("ddzdh")) ? "" : map.get("ddzdh").toString());//联系方式
                btyTxlRY2.setSsctdm(dm);//店名
                //不存在该数据
                if (ddzCount == 0) {
                    mapper.addfzr(btyTxlRY2);
                } else {
                    mapper.updateTxlRY(btyTxlRY2);
                }

                //查询表中是否存在该数据
                int dzCount = mapper.selectCount(dm, "店长");
                //bty_txl_ry表新增数据
                BtyTxlRY btyTxlRY1 = new BtyTxlRY();
                btyTxlRY1.setZw("店长");//职务(店长)
                btyTxlRY1.setFzr(ToolUtil.isEmpty(map.get("kqDz")) ? "" : map.get("kqDz").toString());//负责人
                btyTxlRY1.setLxfs(ToolUtil.isEmpty(map.get("kqDh")) ? "" : map.get("kqDh").toString());//联系方式
                btyTxlRY1.setSsctdm(dm);//店名
                //不存在该数据
                if (dzCount == 0) {
                    mapper.addfzr(btyTxlRY1);
                } else {
                    mapper.updateTxlRY(btyTxlRY1);
                }
            }
        }

        return ResponseData.success();
    }

    /**
     * 同步外卖店名
     * @return
     */
    public ResponseData editWmDm() {
        //获取外卖通讯录中所有数据
        List<Map> list = baseMapper.getWmList();
        if (ToolUtil.isNotEmpty(list)){
            //每150条保存一次
            for(int i = 0; i < list.size();){
                int i2 = (i + 150);
                i2 = i2 > list.size() ? list.size() : i2;
                List<Map> sub = list.subList(i, i2);
                this.mapper.updateList(sub);
                i = i2;
            }
        }
        return ResponseData.success();
    }

    /**
     * 批量修改通讯录中法人和食品经营许可截止日期
     * @param list
     */
    public void editTxl(List<Map> list) {
        this.mapper.editTxl(list);
    }

    public List<Map<String, Object>> listCwmAll() {
        return this.baseMapper.listCwmAll();
    }

    public void updateCwm(BtyTxl btyTxl){
        baseMapper.updateCwm(btyTxl);
    }

    public void updateCwms(BtyTxl btyTxl){
        baseMapper.updateCwms(btyTxl);
    }
}
